//
//  SortSleepView.m
//  project
//
//  Created by 黄建华 on 2019/1/11.
//  Copyright © 2019年 黄建华. All rights reserved.
//

#import "SortSleepView.h"

@implementation SortSleepView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self performSelector:@selector(createChartView) withObject:nil afterDelay:IOSINITWAITTIME];
    }
    return self;
}

- (void)createChartView {
    self.backgroundColor = [UIColor whiteColor];
}

// 更新数据
// 1 为睡眠时长 2 为入睡时间
- (void)UpdateViewWithType:(SelectDateType)type withArray:(NSArray *)dataArray withCurrent:(NSInteger)current withSleepType:(NSInteger)sleepType
{
     [self loadBackgroundLayer];

    //数据加载
    NSMutableArray *array  = [NSMutableArray array];
    for (int i = 0; i <8; i++) {
        [array addObject:@"0"];
    }
    
    NSMutableArray *labelArray1 ;
    NSMutableArray *labelArray3 ;
    
    int currentIndex = 0;
    int currentSleep = 0;
    
//    SleepModel *sleepModel = [SleepModel getSleepModelFromDBWith:[NSDate date]];
    SleepModel *sleepModel = [SleepModel getSleepModelFromDBWith:SN_PublicClass.selectDate];
    if (sleepType == 2) {
        labelArray1 = [NSMutableArray arrayWithArray:@[@"<=20:00",@"20:01",@"21:01",@"22:01",@"23:01",@"00:01",@"01:01",@"≥02:01"]];
        labelArray3 = [NSMutableArray arrayWithArray:@[@"",@"21:00",@"22:00",@"23:00",@"00:00",@"01:00",@"02:00",@""]];
        
        // 第一段睡眠的入睡时间
        if (sleepModel.sleepsubArray.count > 0) {
            SleepSubModel *model = [sleepModel.sleepsubArray firstObject];
            NSString *startString = model.substartTime;
            NSArray *array = [startString componentsSeparatedByString:@" "];
            NSString *time = [array lastObject];
            NSArray *arr = [time componentsSeparatedByString:@":"];
            NSString *time1 = [arr firstObject];
            NSString *time2 = [arr lastObject];
            currentSleep = time1.intValue *60 +time2.intValue;
        }
        else
        {
        currentSleep = 0;
        }
        
    }
    else if(sleepType == 1)
    {
        labelArray1 = [NSMutableArray arrayWithArray:@[@"<05:00",@"05:01",@"06:01",@"07：01",@"08：01",@"09:01",@"10:01",@">11:01"]];
        labelArray3 = [NSMutableArray arrayWithArray:@[@"",@"06:00",@"07:00",@"08:00",@"09:00",@"10:00",@"11:00",@""]];
        currentSleep = sleepModel.durations;
    }
    
    NSMutableArray *valueArray = [NSMutableArray array];
    SortModel *model = [SortModel getSortModelFromDBWithDayString:[[NSDate date]dateToDayString]];
    if (sleepType == 1) {
        for (int k = 0; k <array.count ; k++) {
            if (model.sleepDurationSArray.count >0) {
                NSDictionary *dic = [model.sleepDurationSArray objectAtIndex:k];
                int value = [dic[@"value"]intValue];
                [array replaceObjectAtIndex:k withObject:StrByInt(value)];
                
                int left = [dic[@"left"]intValue];
                int right = [dic[@"right"]intValue];
                NSString *string1 = [NSString stringWithFormat:@"%02d:00",left];
                NSString *string2 = [NSString stringWithFormat:@"%02d:00",right];
                
                [labelArray1 replaceObjectAtIndex:k withObject:string1];
                [labelArray3 replaceObjectAtIndex:k withObject:string2];
//                NSLog(@"currentSleep>>>%d left>>>%d",currentSleep,left*60);
   
                if ((currentSleep >= left*60)&(currentSleep < right*60)) {
                    currentIndex = k;
                }
                [valueArray addObject:StrByInt(value)];
            }
        }
    }
    if (sleepType == 2) {
        for (int k = 0; k <array.count ; k++) {
            if (model.sleepStartArray.count >0) {
                NSDictionary *dic = [model.sleepStartArray objectAtIndex:k];
                int value = [dic[@"value"]intValue];
                [array replaceObjectAtIndex:k withObject:StrByInt(value)];
                
                int left = [dic[@"left"]intValue];
                int right = [dic[@"right"]intValue];
                NSString *string1 = [NSString stringWithFormat:@"%02d:00",left];
                NSString *string2 = [NSString stringWithFormat:@"%02d:00",right];
                
                [labelArray1 replaceObjectAtIndex:k withObject:string1];
                [labelArray3 replaceObjectAtIndex:k withObject:string2];
//                NSLog(@"入睡currentSleep>>>%d left>>>%d",currentSleep,left*60);
                if ((currentSleep >= left*60)&(currentSleep < right*60)) {
                    currentIndex = k;
                }
                [valueArray addObject:StrByInt(value)];
            }
        }
    }
    
    _selectDateLabel               = [[SNCustomLabel alloc] initWithFrame:CGRectMake(5, 10, 200, 20)];
    _selectDateLabel.textAlignment = NSTextAlignmentLeft;
    _selectDateLabel.textColor     = SNCOLORBLACK;
    _selectDateLabel.font          = SNSFONT(14.0);
    //    [_chartView addSubview:_selectDateLabel];
    
    UIView *lineGray = [[UIView alloc] init];
    lineGray.backgroundColor = SNCOLORWITHHEX(0xd7d8d9);
    lineGray.frame           = SNFRAME(5, self.height - 40, HHHWIDTH - 10, 1);
    [_chartView addSubview:lineGray];
    
    _valueLabel               = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0,lineGray.bottom + 38 ,self.width, 20)];
    _valueLabel.adjustsFontSizeToFitWidth = YES;
    _valueLabel.textAlignment = NSTextAlignmentCenter;
    _valueLabel.textColor     = SNCOLORBLACK;
    _valueLabel.font          = SNFONT(14.0);
    [_chartView addSubview:_valueLabel];
    
    _unitLabel               = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0,_valueLabel.bottom - 5, self.width, 30)];
    _unitLabel.textColor     = SNCOLORGRAY;
    _unitLabel.font          = SNSFONT(10.5);
    _unitLabel.textAlignment = NSTextAlignmentCenter;
    _unitLabel.numberOfLines = 2;
    [_chartView addSubview:_unitLabel];
    
    NSInteger maxValue = [self max:array];
    NSInteger minValue = [self min:array];
    
    float   Origin_x      = 10;
    CGFloat Origin_height = self.height - 40;
    CGFloat offsetY       = FitScreenNumber(40, 40, 40, 40, 40);
    
    for (int i = 0; i < array.count; i++) {
        CGFloat value = [[array objectAtIndex:i] floatValue];
        if (value > maxValue) {
            value = maxValue;
        }
        
        CGFloat height = 0;
        CGFloat h      = (self.height - (25 + 30 + offsetY)) * (value / maxValue);
        if (isnan(h)) {
            height = 0;
        } else {
            height = h;
        }
        static int total = 0;
        total = total + value;
        
        CGFloat chartWidth = 0;
        CGFloat chartSpace = 0;
        if (type == 1) {
            Origin_x   = 20;
            chartWidth = 8;
            chartSpace = (self.width - Origin_x *2)/8 + 5;
        }
        
        CGPoint point01 = CGPointMake(i * chartSpace + Origin_x, Origin_height-height);
        CGPoint point02 = CGPointMake((i) * chartSpace + Origin_x +chartWidth, Origin_height-height);
        
        UIBezierPath *fill = [UIBezierPath bezierPath];
        [fill moveToPoint:point01];
        [fill addLineToPoint:point02];
        [fill addLineToPoint:CGPointMake(point02.x, Origin_height)];
        [fill addLineToPoint:CGPointMake(point01.x, Origin_height)];
        
        // 填充区域
        CAShapeLayer *fillLayer = [CAShapeLayer layer];
        fillLayer.frame       = self.bounds;
        fillLayer.bounds      = self.bounds;
        fillLayer.path        = fill.CGPath;
        fillLayer.strokeColor = SNSLEEPCOLORDEEP.CGColor;
        fillLayer.fillColor   = SNSLEEPCOLORDEEP.CGColor;
        fillLayer.lineWidth   = 0.0;
        fillLayer.lineJoin    = kCALineJoinRound;
        [_backGroundLayer addSublayer:fillLayer];
        
        UIBezierPath *noFill = [UIBezierPath bezierPath];
        [noFill moveToPoint:CGPointMake(point01.x, Origin_height)];
        [noFill addLineToPoint:CGPointMake(point02.x, Origin_height)];
        [noFill addLineToPoint:CGPointMake(point02.x, Origin_height)];
        [noFill addLineToPoint:CGPointMake(point01.x, Origin_height)];
        
        // 填充区域过渡动画
        CABasicAnimation *fillAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
        fillAnimation.duration       = SNACTIONTIME;
        fillAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        fillAnimation.fillMode       = kCAFillModeForwards;
        fillAnimation.fromValue      = (id)noFill.CGPath;
        fillAnimation.toValue        = (id)fill.CGPath;
        [fillLayer addAnimation:fillAnimation forKey:@"path"];
        
        //圆角
        UIView *view = [[UIView alloc] init];
        view.frame           = SNFRAME(point01.x, point01.y + height, chartWidth, height==0?0:5);
        view.backgroundColor = SNSLEEPCOLORDEEP;
        [_chartView addSubview:view];
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius  = chartWidth/2;
        view.alpha               = 1;
        
        UIImageView *finishImageView = [[UIImageView alloc] init];
        finishImageView.frame  = SNFRAME(point01.x - 11 + chartWidth/2, point01.y - 20 - chartWidth -5, 22, 22);
        finishImageView.image  = SN_USER.headImage;
        finishImageView.layer.cornerRadius = 11.0;
        finishImageView.layer.masksToBounds = YES;
        //        [_chartView addSubview:finishImageView];
        if (i == currentIndex) {
            [_chartView addSubview:finishImageView];
        }
        
        dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SNACTIONTIME * NSEC_PER_SEC));
        void            (^task)() = ^{
            view.alpha = 1.0;
            view.frame = SNFRAME(point01.x, point01.y - 2, chartWidth, 5);
            if (value == 0) {
                view.alpha = 0.0;
            }
        };
        // 经过多少纳秒，由主队列调度任务异步执行
        dispatch_after(when, dispatch_get_main_queue(), task);
        NSMutableArray *labelArray = [NSMutableArray array];
        
        if (currentSleep == 0) {
            finishImageView.hidden = YES;
        }
        else
        {
         
            finishImageView.hidden = NO;
        }
        

        for (int i = 0; i <labelArray1.count; i++) {
            NSString *s1 = [labelArray1 objectAtIndex:i];
            NSString *s2 = @"－";
//            if (i==0 ||(i == labelArray1.count -1)) {
//                s2 = @"";
//            }
            NSString *s3 = [labelArray3 objectAtIndex:i];
            NSString *string = [NSString stringWithFormat:@"%@\n%@\n%@",s1,s2,s3];
            [labelArray addObject:string];
            
        }
            SNCustomLabel *label     = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0,lineGray.bottom +10, 100, 40)];
            label.center        = CGPointMake(view.center.x,lineGray.bottom + 20);
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor     = SNCOLORGRAY;
            label.font          = SNSFONT(9.0);
            label.text          = [labelArray objectAtIndex:i];
            label.numberOfLines = 3;
            [_chartView addSubview:label];
        
            NSMutableAttributedString *noteStr;
            noteStr = [[NSMutableAttributedString alloc] initWithString:label.text];
            NSUInteger first1 = [[noteStr string] rangeOfString:@"－"].location;
            // 需要改变的区间
            NSRange range1 = NSMakeRange(first1,@"－".length);
            [noteStr addAttribute:NSFontAttributeName value:SNFONT(11) range:range1];
            label.attributedText = noteStr;
    }
    
//    NSLog(@"valueArray>>>>%@",valueArray);
    int more = 0;
    for (int k = 0; k <currentIndex; k++) {
        more += [[valueArray objectAtIndex:k]intValue];
    }

    int sum = [[valueArray valueForKeyPath:@"@sum.floatValue"] intValue];
    float vvv = 1.0 *more/sum *100;

    //当前步数区间
//    int currentStepS = [[labelArray3 objectAtIndex:currentIndex]intValue];
//    float currentVVV = 1.0*currentSleep / currentStepS*60 *100;
    float v = vvv;
    
    if (currentIndex == 0) {
        if (sleepModel.durations > 0) {
            v = 1.0;
        }
        else
        {
            v = 1.0;
        }
        
    }
    if (currentIndex == valueArray.count -1) {
        v = 99.0;
    }
//

//    
//    
//    NSLog(@">>>>>%d",vvv);
    
    if (sleepType == 1) {
        if (more == 0) {
            v = 1.0;
        }
        _valueLabel.text = [NSString stringWithFormat:@"%@ %.0f%% %@",SN_Text(@"你的睡眠时长超过了"),v,SN_Text(@"用户")];
        NSString *sleepInfo = SN_Text(@"呃，睡这么久是不是头有点昏?");
        if (currentSleep >=0) {
            sleepInfo = SN_Text(@"你的睡眠时长过短，请注意休息");
        }
        if (currentSleep >7*60+1) {
            sleepInfo = SN_Text(@"还不错的睡眠时长");
        }
        if (currentSleep >8*60+1) {
            sleepInfo = SN_Text(@"你拥有了令人羡慕的睡眠");
        }
        if (currentSleep >9*60+1) {
            sleepInfo = SN_Text(@"精力充沛的一天");
        }
        if (currentSleep >10*60+1) {
            sleepInfo = SN_Text(@"睡眠时间有点长");
        }
        if (currentSleep >11*60+1) {
            sleepInfo = SN_Text(@"呃，睡这么久是不是头有点昏?");
        }
        
        _unitLabel.text = sleepInfo;
    }
    else if (sleepType == 2)
    {
        if (more == 0) {
            v = 99.0;
        }
        _valueLabel.text = [NSString stringWithFormat:@"%@ %.0f%% %@",SN_Text(@"入睡时间晚于"),v,SN_Text(@"用户")];
        NSString *sleepInfo = SN_Text(@"长期熬夜会使患心血管疾病几率增加36%");
        if (currentSleep >=12*60 && currentSleep < 20*60) {
            sleepInfo = SN_Text(@"请检查是否有正确佩戴设备");
        }
        if (currentSleep >=12*60 && currentSleep < 20*60) {
            sleepInfo = SN_Text(@"令人羡慕的入睡时间");
        }
        if (currentSleep >=12*60 && currentSleep < 20*60) {
            sleepInfo = SN_Text(@"最健康的入睡时间");
        }
        if (currentSleep >=12*60 && currentSleep < 20*60) {
            sleepInfo = SN_Text(@"合理的入睡时间是优秀睡眠的重要条件");
        }
        if (currentSleep >=12*60 && currentSleep < 20*60) {
            sleepInfo = SN_Text(@"睡前播放轻松的音乐有助睡眠");
        }
        if (currentSleep >=12*60 && currentSleep < 20*60) {
            sleepInfo = SN_Text(@"0-1点是肝脏开始排毒的时间");
        }
        if (currentSleep >=12*60 && currentSleep < 20*60) {
            sleepInfo = SN_Text(@"今天早点休息，不要熬夜");
        }
        if (currentSleep >=12*60 && currentSleep < 20*60) {
            sleepInfo = SN_Text(@"长期熬夜会使患心血管疾病几率增加36%");
        }
        
        _unitLabel.text = sleepInfo;
    }
}

- (NSInteger)max:(NSArray *)Array {
    if (Array.count == 0) {
        return 0;
    }
    
    NSInteger max = [[Array objectAtIndex:0] integerValue];
    
    for (int i = 0; i < Array.count; i++) {
        if ([[Array objectAtIndex:i] integerValue] > max) {
            max = [[Array objectAtIndex:i] integerValue];
        }
    }
    
    return max;
}

- (NSInteger)min:(NSArray *)Array {
    if (Array.count == 0) {
        return 0;
    }
    
    NSInteger min = [[Array objectAtIndex:0] integerValue];
    
    for (int i = 0; i < Array.count; i++) {
        if ([[Array objectAtIndex:i] integerValue] < min) {
            min = [[Array objectAtIndex:i] integerValue];
        }
    }
    return min;
}

- (void)loadBackgroundLayer {
    if (_chartView) {
        [_chartView removeFromSuperview];
        _chartView = nil;
    }
    
    _chartView                 = [[UIView alloc] init];
    _chartView.backgroundColor = [UIColor whiteColor];
    _chartView.frame           = CGRectMake(0, 0, self.width, self.height);
    [self addSubview:_chartView];
    
    if (_backGroundLayer) {
        [_backGroundLayer removeFromSuperlayer];
        _backGroundLayer = nil;
    }
    _backGroundLayer                 = [CALayer layer];
    _backGroundLayer.backgroundColor = [UIColor clearColor].CGColor;
    _backGroundLayer.bounds          = CGRectMake(0, 0, self.width, self.height);
    _backGroundLayer.position        = CGPointMake(self.center.x, self.height / 2);
    [_chartView.layer addSublayer:_backGroundLayer];
}

@end
